
#pragma once

#include <nxos/device.h>

inline NX_Solt NX_IoBlockOpen(const char *name)
{
    if (!name)
    {
        return NX_SOLT_INVALID_VALUE;
    }
    return NX_DeviceOpen(name, 0);
}

inline void NX_IoBlockSync(NX_Solt blk)
{
    NX_DeviceControl(blk, 2, NX_NULL);
}

inline NX_Error NX_IoBlockClose(NX_Solt blk)
{
    if (blk == NX_SOLT_INVALID_VALUE)
    {
        return NX_EINVAL;
    }
    return NX_DeviceClose(blk);
}

#define NX_IO_BLOCK_INFO 1
#define NX_IO_BLOCK_SYNC 2

typedef struct NX_IoBlockInfo
{
    NX_Size blockSize;
    NX_Size blockCount;
    NX_Size capacity;
} NX_IoBlockInfo;

inline NX_Size NX_IoBlockCapacity(NX_Solt blk)
{
    if (blk == NX_SOLT_INVALID_VALUE)
    {
        printf("blk == NX_SOLT_INVALID_VALUE\n");
        return 0;
    }
    NX_IoBlockInfo info;
    NX_Error err = NX_DeviceControl(blk, NX_IO_BLOCK_INFO, &info);
    if (err != NX_EOK)
    {
        printf("NX_DeviceControl failed! %s\n", NX_ErrorToString(err));
        return 0;
    }
    return info.capacity;
}

inline NX_Size NX_IoBlockWrite(NX_Solt blk, NX_U8 *buf, NX_Offset offset, NX_Size count)
{
    if (!blk || !buf || !count)
    {
        return 0;
    }

    NX_Size ret = NX_DeviceWrite(blk, buf, offset, count);
    // NX_Size ret = 0;
    // NX_Error err = NX_DeviceWrite(blk, buf, offset, count, &ret);
    // if (err != NX_EOK)
    // {
    //     NX_LOG_E("io block write failed! %s", NX_ErrorToString(err));
    //     ret = 0;
    // }
    return ret;
}

inline NX_Size NX_IoBlockRead(NX_Solt blk, NX_U8 *buf, NX_Offset offset, NX_Size count)
{
    if (!blk || !buf || !count)
    {
        return 0;
    }
    NX_Size ret = NX_DeviceRead(blk, buf, offset, count);
    return ret;
}
